import { app, BrowserWindow } from "electron";
import { fileURLToPath } from "node:url";
import path from "node:path";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

// 项目根目录
process.env.APP_ROOT = path.join(__dirname, "..");

// 定义构建输出目录
export const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
export const MAIN_DIST = path.join(process.env.APP_ROOT, "dist-electron");
export const RENDERER_DIST = path.join(process.env.APP_ROOT, "dist");

// 设置公共资源目录
process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL
  ? path.join(process.env.APP_ROOT, "public")
  : RENDERER_DIST;

let win: BrowserWindow | null;

function createWindow() {
  win = new BrowserWindow({
    width: 1200,
    height: 900,
    icon: path.join(process.env.VITE_PUBLIC, "electron-vite.svg"),
    webPreferences: {
      preload: path.join(__dirname, "preload.mjs"),
      nodeIntegration: false,
      contextIsolation: true,
      webSecurity: false,
    },
  });

  // 主进程到渲染进程的消息推送（测试用）
  win.webContents.on("did-finish-load", () => {
    win?.webContents.send("main-process-message", new Date().toLocaleString());
  });
  console.log("VITE_DEV_SERVER_URL", VITE_DEV_SERVER_URL);

  // 开发模式：加载 Vite 开发服务器
  if (VITE_DEV_SERVER_URL) {
    const indexPath = path.join(RENDERER_DIST, "index.html");
    console.log("Loading index.html from:", indexPath); // 调试路径
    win.loadURL(indexPath).catch((err) => {
      console.error("Failed to load index.html:", err);
    });
  }
  // 生产模式：加载打包后的 index.html
  else {
    const indexPath = path.join(RENDERER_DIST, "index.html");
    console.log("Loading index.html from:", indexPath); // 调试路径
    win.loadFile(indexPath).catch((err) => {
      console.error("Failed to load index.html:", err);
    });
  }
}

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    win = null;
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

app.whenReady().then(createWindow);
